<template>
    <div>
        <!-- 选择拆几份 -->
        <div v-if="chooseActive == 1">
            <div class="one_active_choose">
                <el-input-number v-model="splitNum" @change="handleChangeSplitNum" :min="1"
                    label="份数"></el-input-number>
                <div class="one_active_choose_mark">剩余商品自动保存一份订单，不需要计算进入该份数</div>
            </div>
        </div>
        <!-- 选择商品 -->
        <div v-if="chooseActive == 2">
            <el-tabs type="border-card" @tab-click="clickChooseSplitNum">
                <el-tab-pane v-for="(item, index) in splitNum" :key="index">
                    <span slot="label">第{{item}}份</span>
                    <div style="width: 25%;">
                        <el-input v-model="searchGoodKeyword" size="mini" @change="searchGood" clearable
                            placeholder="请输入商品名称"></el-input>
                    </div>
                    <el-table
                        :data="showGoodList.filter(data => !searchGoodKeyword || data.goodName.toLowerCase().includes(searchGoodKeyword.toLowerCase()))"
                        height="450" :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }" style="width: 100%">
                        <el-table-column prop="chooseNum" width="150" label="选择的数量">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.chooseNum" @change="handleChangeChooseNum" :min="0"
                                    :max="scope.row.maxNum" label="请填写数量" size="mini"
                                    controls-position="right"></el-input-number>
                                <div>可填最大值：{{ scope.row.maxNum }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="goodName" label="商品名称" width="180">
                        </el-table-column>
                        <el-table-column prop="goodSku" label="规格" width="180">
                        </el-table-column>
                        <el-table-column prop="goodSkuNum" width="150" label="数量">
                        </el-table-column>
                        <el-table-column prop="goodSkuPrice" width="180" label="价格">
                        </el-table-column>
                        <el-table-column prop="goodSkuPic" width="150" label="图片">
                            <template slot-scope="scope">
                                <el-image v-if="scope.row.goodSkuPic" style="width: 100px; height: 100px"
                                    :src="scope.row.goodSkuPic" :preview-src-list="[scope.row.goodSkuPic]">
                                </el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="goodExpirationDate" width="180" label="有效期">
                        </el-table-column>
                        <el-table-column prop="goodWarrantyDate" width="180" label="保质期">
                        </el-table-column>
                        <el-table-column prop="goodOnlineLink" width="180" show-overflow-tooltip label="网上链接">
                            <template slot-scope="scope">
                                <div v-if="scope.row.goodOnlineLink">
                                    <el-button type="text" @click="goNewPage(scope.row.goodOnlineLink)">跳转</el-button>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="goodBoxNum" width="180" label="箱规（数量）">
                        </el-table-column>
                        <el-table-column prop="goodBoxSize" width="180" label="箱规（尺寸mm）">
                        </el-table-column>
                        <el-table-column prop="goodOneSize" width="180" label="单个产品包装尺寸mm">
                        </el-table-column>
                        <el-table-column prop="shopFans" width="180" label="店铺粉丝量">
                        </el-table-column>
                        <el-table-column prop="goodSaleNum" width="180" label="产品销量">
                        </el-table-column>
                        <el-table-column prop="finalPrice" width="180" label="旗舰店实际成交价">
                        </el-table-column>
                        <el-table-column prop="realReadPrice" width="180" label="实际成交价">
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 用列表分别展示各自的商品列表 -->
        <div v-if="chooseActive == 3">
            <div>
                <div class="showFinal" v-for="(item, key, index) in chooseGoodMap" :key="index">
                    <el-descriptions :title="key == 'otherList' ? '剩余' : ('第' + key + '份子订单')">
                        <el-descriptions-item label="订单总货值">{{ subOrderOtherMap[key].totalPrice
                            }}</el-descriptions-item>
                        <el-descriptions-item label="订单走向">
                            <el-select v-model="subOrderOtherMap[key].useType" placeholder="请选择"
                                @change="$forceUpdate()">
                                <el-option v-for="item in moreOptionsList" :key="item.id" :label="item.sysValueName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-descriptions-item>
                        <el-descriptions-item label="预计变现">
                            <el-input-number v-model="subOrderOtherMap[key].expectPrice" :precision="2" :min="0"
                                label="预计变现" @change="$forceUpdate()"></el-input-number>
                        </el-descriptions-item>
                    </el-descriptions>
                    <div>
                        <el-collapse v-model="showModelActiveNames" @change="handleChangeShowModelGoodList">
                            <el-collapse-item :name="key">
                                <template slot="title">
                                    商品列表
                                </template>
                                <el-table :data="item" height="350" :row-style="{ height: '0' }"
                                    :cell-style="{ padding: '3px' }" style="width: 100%">
                                    <el-table-column prop="goodName" label="商品名称" width="180">
                                    </el-table-column>
                                    <el-table-column prop="goodSku" label="规格" width="180">
                                    </el-table-column>
                                    <el-table-column prop="chooseNum" width="150" label="数量">
                                    </el-table-column>
                                    <el-table-column prop="goodSkuPrice" width="180" label="价格">
                                    </el-table-column>
                                    <el-table-column prop="goodSkuPic" width="150" label="图片">
                                        <template slot-scope="scope">
                                            <el-image v-if="scope.row.goodSkuPic" style="width: 100px; height: 100px"
                                                :src="scope.row.goodSkuPic" :preview-src-list="[scope.row.goodSkuPic]">
                                            </el-image>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="goodExpirationDate" width="180" label="有效期">
                                    </el-table-column>
                                    <el-table-column prop="goodWarrantyDate" width="180" label="保质期">
                                    </el-table-column>
                                    <el-table-column prop="goodOnlineLink" width="180" show-overflow-tooltip
                                        label="网上链接">
                                        <template slot-scope="scope">
                                            <div v-if="scope.row.goodOnlineLink">
                                                <el-button type="text"
                                                    @click="goNewPage(scope.row.goodOnlineLink)">跳转</el-button>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="goodBoxNum" width="180" label="箱规（数量）">
                                    </el-table-column>
                                    <el-table-column prop="goodBoxSize" width="180" label="箱规（尺寸mm）">
                                    </el-table-column>
                                    <el-table-column prop="goodOneSize" width="180" label="单个产品包装尺寸mm">
                                    </el-table-column>
                                    <el-table-column prop="shopFans" width="180" label="店铺粉丝量">
                                    </el-table-column>
                                    <el-table-column prop="goodSaleNum" width="180" label="产品销量">
                                    </el-table-column>
                                    <el-table-column prop="finalPrice" width="180" label="旗舰店实际成交价">
                                    </el-table-column>
                                    <el-table-column prop="realReadPrice" width="180" label="实际成交价">
                                    </el-table-column>
                                </el-table>
                            </el-collapse-item>
                        </el-collapse>
                    </div>
                </div>
            </div>
        </div>
        <span class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" v-if="chooseActive > 2" @click="beforeChooseActive">上一步</el-button>
            <el-button type="primary" v-if="chooseActive < 3" @click="nextChooseActive">下一步</el-button>
            <el-button type="primary" v-if="chooseActive == 3" @click="commitChooseActive">提交</el-button>
        </span>
    </div>
</template>

<script>
import APIOrder from "@/api/apiOrder";
import APISysLabel from "@/api/apiSysLabel";

export default {
    name: "SplitOrder",
    components: {
    },
    props: {
        orderId: Number,
        splitOrderType: Number,
        projectId:Number,
        currentStageid:Number
    },
    watch: {
        orderId(val) {
            if (val) {
                this.getViewMsg()
            }
        },
        projectId(val) {
            if (val) {
                this.getViewMsg()
            }
        },
    },
    data() {
        return {
            chooseActive: 1, // 第一步选择拆几份订单，第二步选择商品，第三步对拆出来的订单进行对应的处理
            modelGoodList: [],
            showGoodList: [],
            showModelActiveNames: [],
            splitNum: 1,
            chooseGoodMap: {},
            showSplitNum: 1, // 表示当前选择的是第几个拆单
            searchGoodKeyword: '',
            subOrderOtherMap: {}, // 子订单对应的其他数据
            moreOptionsList: [],
            parentId:null
        };
    },
    activated(){
        if (this.orderId || this.projectId){
            this.getViewMsg()
        }
    },
    created() {
        if (this.orderId || this.projectId) {
            this.getViewMsg()
        }
        console.log(this.orderId,this.projectId)
    },
    methods: {
        commitChooseActive(){
            let noCommit = false
            let goodMap = {}
            let useTypeMap = {}
            for (let key in this.subOrderOtherMap) {
                if (!this.subOrderOtherMap[key].useType){
                    noCommit = true
                }
                useTypeMap[key] = {
                    useType: this.subOrderOtherMap[key].useType,
                    expectPrice: this.subOrderOtherMap[key].expectPrice,
                }
            }
            if (noCommit) {
                this.$message.error("请选择订单走向")
                return
            }
            for (let key in this.chooseGoodMap) {
                let list = this.chooseGoodMap[key]
                let finalList = []
                list.forEach(item => {
                    finalList.push({
                        goodId: item.id,
                        skuId: item.goodSkuId,
                        num: item.chooseNum,
                    })
                })
                goodMap[key] = finalList
            }
            console.log(this.orderId,11111111)
            let params = {
                fileType: 1,
                parentId: this.orderId===null? this.parentId:this.orderId,
                orderStr: JSON.stringify(goodMap),
                useTypeStr: JSON.stringify(useTypeMap),
            }
            if (this.splitOrderType && this.splitOrderType == 2) {
                APIOrder.doSplitOrderAfterBidding(params).then(res => {
                    if (res.key === 1000) {
                        this.$message.success('分单成功');
                        this.$emit("doRefushSplitOrder")
                    }
                })
            }else{
                APIOrder.doSplitOrder(params).then(res => {
                    if (res.key === 1000) {
                        this.$message.success('分单成功');
                        this.$emit("doRefushSplitOrder")
                    }
                })
            }
        },
        getMoreOptionsList() {
            const params = {
                token: this.$store.state.token,
                sysLabelIds: 42,
            };
            APISysLabel.getSysLabelValueManageList(params).then((res) => {
                if (res.key === 1000) {
                    this.moreOptionsList = res.result.data[42]
                }
            });
        },
        searchGood(){
        },
        changeModelGoodList(){
            if (this.chooseGoodMap[this.showSplitNum]) {
                let modelList = JSON.parse(JSON.stringify(this.modelGoodList))
                modelList.forEach(modelItem => {
                    modelItem.chooseNum = 0
                    modelItem.maxNum = modelItem.goodSkuNum
                })
                let list = this.chooseGoodMap[this.showSplitNum]
                list.forEach(item => {
                    modelList.forEach(modelItem => {
                        if (item.id == modelItem.id && item.goodSkuId == modelItem.goodSkuId) {
                            modelItem.chooseNum = item.chooseNum
                        }
                    })
                })
                for (var i = 0; i < this.splitNum; i++) {
                    let list = this.chooseGoodMap[i + 1]
                    list.forEach(item => {
                        modelList.forEach(modelItem => {
                            if (item.id == modelItem.id && item.goodSkuId == modelItem.goodSkuId) {
                                modelItem.maxNum = JSON.parse(JSON.stringify(modelItem.maxNum)) - item.chooseNum
                            }
                        })
                    })
                    if ((i + 1) == this.showSplitNum) {
                        list.forEach(item => {
                            modelList.forEach(modelItem => {
                                if (item.id == modelItem.id && item.goodSkuId == modelItem.goodSkuId) {
                                    modelItem.maxNum = modelItem.maxNum + item.chooseNum
                                }
                            })
                        })
                    }
                }
                this.modelGoodList = modelList
                this.showGoodList = modelList
            }
        },
        clickChooseSplitNum(val){
            this.showSplitNum = JSON.parse(JSON.stringify(Number(val.index) + 1))
            this.searchGoodKeyword = ''
            this.changeModelGoodList()
        },
        clearModelGoodList(){
            this.showGoodList.forEach(item => {
                item.chooseNum = 0
            })
            this.modelGoodList.forEach(item => {
                item.chooseNum = 0
            })
        },
        handleChangeChooseNum(val){
            let showList = this.showGoodList
            let list = this.modelGoodList
            showList.forEach(showItem => {
                list.forEach(item => {
                    if (showItem.id == item.id && item.goodSkuId == showItem.goodSkuId){
                        item.chooseNum = showItem.chooseNum
                    }
                })
            })
            let chooseList = []
            list.forEach(item => {
                if (item.chooseNum && item.chooseNum != 0 && item.chooseNum > 0){
                    chooseList.push(item)
                }
            })
            this.chooseGoodMap[this.showSplitNum] = chooseList
        },
        beforeChooseActive() {
            if (this.chooseActive > 2){
                this.chooseActive -= 1
            }else{
                this.chooseActive = 2
            }
            if (this.chooseActive == 2){
                this.showSplitNum = 1
                this.searchGoodKeyword = ''
                this.changeModelGoodList()
            }
        },
        nextChooseActive() {
            if (this.chooseActive == 2) {
                // 拆单分配完数量后点击下一步的时候，先判断是否有商品分配，如果所有的子订单的商品都没有分配过，那么提示进行分配数量
                let hasAddChooseGood = false
                for(var i = 0;i < this.splitNum; i++){
                    if (this.chooseGoodMap[i + 1] && this.chooseGoodMap[i + 1].length > 0){
                        hasAddChooseGood = true
                        break
                    }
                }
                if (!hasAddChooseGood){
                    this.$message.error("请分配子订单的商品数量")
                    return
                }
            }
            this.chooseActive += 1
            if(this.chooseActive == 2){
                // 拆单分配每个子订单的商品数量
                for(var i=0;i< this.splitNum; i++){
                    this.chooseGoodMap[i + 1] = []
                }
            }
            if (this.chooseActive == 3){
                // 获取剩余商品列表
                let modelList = JSON.parse(JSON.stringify(this.modelGoodList))
                let otherList = []
                modelList.forEach(modelItem => {
                    modelItem.maxNum = modelItem.goodSkuNum
                })
                for (var i = 0; i < this.splitNum; i++) {
                    let list = this.chooseGoodMap[i + 1]
                    list.forEach(item => {
                        modelList.forEach(modelItem => {
                            if (item.id == modelItem.id && item.goodSkuId == modelItem.goodSkuId) {
                                modelItem.maxNum = modelItem.maxNum - item.chooseNum
                            }
                        })
                    })
                }
                modelList.forEach(item => {
                    if (item.maxNum && item.maxNum != 0 && item.maxNum > 0) {
                        item.chooseNum = item.maxNum
                        otherList.push(item)
                    }
                })
                this.chooseGoodMap["otherList"] = otherList
                for(let key in this.chooseGoodMap){
                    let totalPrice = 0
                    let list = this.chooseGoodMap[key]
                    list.forEach(item => {
                        totalPrice += item.chooseNum * item.goodSkuPrice
                    })
                    this.subOrderOtherMap[key] = {
                        totalPrice: totalPrice,
                        expectPrice: 0,
                        useType: null,
                    }
                }
                this.getMoreOptionsList()
            }
        },
        closeDialog(){
            this.$emit("closeDialog")
        },
        handleChangeSplitNum(val){},
        handleChangeShowModelGoodList(val){},
        getViewMsg() {
            this.chooseActive = 1
            this.splitNum = 1
            const params = {};
            if(this.orderId!==null){
                params.orderId=this.orderId;
            }else{
                params.projectId=this.projectId;
            }
            params.stageId = this.currentStageid;
            APIOrder.getOrderMsg(params).then((res) => {
                if (res.key === 1000) {
                    let data = res.result.data;
                    data.goodList.forEach(item => {
                        item.maxNum = item.goodSkuNum
                    })
                    this.modelGoodList = data.goodList
                    this.showGoodList = data.goodList
                    this.parentId = data.id
                    this.clearModelGoodList()
                }
            });
        },
    },
};
</script>

<style scoped>
.one_active_choose{
    margin: 10px 0;
    display: flex;
}
.one_active_choose_mark{
    padding-left: 10px;
    display: flex;
    align-items: center;
    margin: 10px 0;
}
.dialog-footer{
    display: flex;
    justify-content: center;
    margin: 10px 0;
}
.showFinal{
    margin: 20px 0;
}
</style>
